#include "pwm.h"

/*
PWM公式：
PWM频率：Freq = CK_PSC/(PSC+1)/(ARR+1)
PWM占空比：Duty = CCR/(ARR+1)
PWM分辨率：Reso = 1/(ARR+1)

eg:要一个频率为1KHZ，占空比为50%，分辨率为1%的pwm波
PWM频率：72MHZ/(PSC+1)/(ARR+1)=1000
PWM占空比：CCR/(ARR+1)=50%
1/(ARR+1) = 1%
*/

void PWM_Init(void)
{
	//使能GPIOA时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	//配置GPIO口功能
	GPIO_InitTypeDef GPIOA_InitStruct;
	GPIOA_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
	//只有将io设置为复用推挽输出，io的控制权=才能交给片上外设，PWM的波形才能通过引脚输出
	GPIOA_InitStruct.GPIO_Pin = GPIO_Pin_0;
	GPIOA_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIOA_InitStruct);
	//初始化GPIO引脚的初始熄灭状态
	GPIO_SetBits(GPIOA,GPIO_Pin_0);
	
	//1.RCC开时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
	//2.选择时钟源
	TIM_InternalClockConfig(TIM2);//不调用这个函数也是默认使用内部时钟
	//3.配置时基单元
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	//定时频率=时钟频率/(PSC+1)/(ARR+1)  
	TIM_TimeBaseInitStructure.TIM_Period = 100-1;//重装载  周期ARR
	TIM_TimeBaseInitStructure.TIM_Prescaler = 720-1;//预分频（越小频率越高）PSC
	//上诉配置定时器周期为1s
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;//高级定时器，不用的话给0
	
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
	
	//4.初始化PWM输出比较
	TIM_OCInitTypeDef TIM_OCInitStructure;
	
	//5.TIM_OCStructInit可以给结构体付初始值，防止出现问题
	TIM_OCStructInit(&TIM_OCInitStructure);
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//输出比较模式
	TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCPolarity_High;//输出比较极性
	TIM_OCInitStructure.TIM_OCNIdleState = TIM_OutputState_Enable;//输出使能
	TIM_OCInitStructure.TIM_Pulse = 0;//设置CCR   pwm由ARR、PSC、CCR决定pwm的占空比
	
	
	TIM_OC1Init(TIM2,&TIM_OCInitStructure);
	//4.使能计数器
	TIM_Cmd(TIM2,ENABLE);
}

void PWM_SetCompare1(uint16_t compare)
{
	TIM_SetCompare1(TIM2, compare);
}